package org.servlet;

import org.entity.User;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建 Servlet 程序，实现转换大写
 *
 * @author zqx
 * @date 2024-06-13
 */
@WebServlet("/change.do")
public class LetterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 第一：获取页面发送过来的数据
        String lowerCase = req.getParameter("letters");

        // 第二：加工处理 - 结果 - 计算 - DAO对象
        String upperCase = lowerCase.toUpperCase() ;

        // 第三：把结果设置在作用域对象中
        // 作用域对象的作用：都是把 Servlet 中的数据传递给JSP页面
        // 区别于：作用范围不一样（有效期） - 请求作用域(99.9%)
        // 1.请求作用域
        req.setAttribute("upperCase",upperCase);

        // 2.会话作用域
        HttpSession session = req.getSession();
        session.setAttribute("name","zhangsan");

        // 3.上下文作用域
        ServletContext context = req.getServletContext();
        context.setAttribute("age",18);

        User user1 = new User("zhangsan",18) ;
        User user2 = new User("lisi",28) ;
        User user3 = new User("wangwu",38) ;
        User user4 = new User("zhaoliu",48) ;

        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);

        req.setAttribute("list",list);


        // 第四：页面跳转（JSP） - 响应结果
        req.getRequestDispatcher("data.jsp").forward(req,resp);

    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
